package stagefour.service.impl;

import stagefour.dao.UserDao;
import stagefour.dao.impl.UserDaoImpl;
import stagefour.model.ResultModel;
import stagefour.model.UserModel;
import stagefour.service.UserService;
import stagefour.util.Md5;

import java.util.ArrayList;
import java.util.List;


public class UserServiceImpl implements UserService {

    private UserDao userDao = new UserDaoImpl();

    @Override
    public ResultModel findAll(){
        List<UserModel> userModelList = userDao.findAll();
        return ResultModel.getResult(userModelList, userModelList.size());
    }

    @Override
    public ResultModel selectUser(String username){

        StringBuffer sql = new StringBuffer("select * from user where");
        List<Object> list = new ArrayList<Object>();
        if (username != null) {

            sql.append(" username = ?");
            list.add(username);

            return ResultModel.getResult(userDao.selectUser(sql.toString(), list));
        }
        return null;
    }

    @Override
    public ResultModel getUser(Integer userid) {
        return ResultModel.getResult(userDao.getUser(userid));
    }

    @Override
    public ResultModel addUser(UserModel userModel) {
        userModel.setPassword(Md5.encoderByMd5(userModel.getPassword()));
        return ResultModel.getResult(userDao.addUser(userModel));
    }

    @Override
    public ResultModel updateUser(UserModel userModel) {
        userModel.setPassword(Md5.encoderByMd5(userModel.getPassword()));
        return ResultModel.getResult(userDao.updateUser(userModel));
    }

    @Override
    public ResultModel deleteUser(Integer userid) {
        return ResultModel.getResult(userDao.deleteUser(userid));
    }
    @Override
    public ResultModel login(UserModel userModel) {
        userModel.setPassword(Md5.encoderByMd5(userModel.getPassword()));
        return ResultModel.getResult(userDao.findByUsernameAndPassword(userModel));
    }

    @Override
    public ResultModel changePassword(UserModel userModel, String newPassword) {
        if(userDao.findByUsernameAndPassword(userModel)){
            userModel.setPassword(newPassword);
            return updateUser(userModel);
        }

        return ResultModel.getResult(false);
    }
}
